#!/usr/bin/env python

import wsgiref.handlers
import time
from douban import Constants
from douban import oAuth
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.api import urlfetch

class MainPage(webapp.RequestHandler):
    def get(self):                
        oauth_consumer_key = Constants.API_KEY
        oauth_signature_method = Constants.SIGNATURE_METHOD
        key = '%s&' % oAuth.escape(Constants.API_KEY_SECRET)        
        oauth_signature = oAuth.escape(key)
        oauth_timestamp = str(int(time.time()))
        oauth_nonce = oAuth.generate_nonce(8)

        unAuth_URL = ["http://www.douban.com/service/auth/request_token",
                      "?oauth_consumer_key=",
                      oauth_consumer_key,
                      "&amp;oauth_signature_method=",
                      oauth_signature_method,
                      "&amp;oauth_signature=",
                      oauth_signature,
                      "&amp;oauth_timestamp=",
                      oauth_timestamp,
                      "&amp;oauth_nonce=",
                      oauth_nonce
                     ]
                
        url = ''.join(unAuth_URL)
        
        try:
            result = urlfetch.fetch(url)
            if result.status_code == 200:            
                xmlStr = result.content
                
                repList = xmlStr.split("&")            
                Req_Token = repList[1].split("=")[1]
                Req_Token_Secret = repList[0].split("=")[1]
                
                oauth_callback = "&amp;oauth_callback=http://%s:%s/douban/token/access?" % (Constants.IP, Constants.PORT)
                
                auth_URL = ["http://www.douban.com/service/auth/authorize",
                            "?oauth_token=",
                            Req_Token,
                            oauth_callback,                        
                            "token_secret=",
                            Req_Token_Secret
                            ]
                url = ''.join(auth_URL)            
                            
                self.redirect(url)
        except:
            url = "/douban/template/timeout.html"
            self.redirect(url)
            
def main():
    application = webapp.WSGIApplication([('/douban', MainPage)],debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
    main()    
